<template>
  <div class="create">
    <div class="cate-list" v-if="cateList.length > 0">
      <a-badge
        v-for="(item, index) of cateList"
        :key="index"
        :count="item.application_total"
        :number-style="{
          backgroundColor: currentCateId == item.id ? 'rgb(255, 101, 98)' : '#FFF',
          color: currentCateId == item.id ? '#fff' : 'rgb(255, 101, 98)',
          boxShadow: 'none',
        }"
      >
        <div
          class="cate-item"
          :class="currentCateId == item.id ? 'cate-item-current' : ''"
          @click="onCateClick(item)"
        >
          <img
            :src="item.cat_icon"
            alt=""
            class="cate-item-icon"
            v-if="item.cat_icon"
          />
          <cu-icon
            v-else-if="item.cat_name == '全部'"
            type="icon-yingyong"
            style="font-size: 30px"
          ></cu-icon>
          <div class="cate-item-name">{{ item.cat_name }}</div>
        </div>
      </a-badge>
    </div>

    <div class="app-list hide-scroller-bar" v-if="appList.length > 0">
      <div
        class="app-card"
        v-for="(item, index) in appList"
        :key="index"
        @click="onAppClick(item)"
      >
        <div class="flex align-center">
          <div class="app-card__image">
            <img :src="item.icon" />
          </div>
          <div class="app-card__title">
            {{ item.name }}
          </div>
        </div>
        <div class="app-card__info">
          {{ item.info }}
        </div>
        <div class="app-card__icon" @click.stop="onCollectClick(item)">
          <CuIcon
            class="app-card__icon--shoucang"
            :type="
              collectAppIds.includes(item.id)
                ? 'icon-shoucang2'
                : 'icon-shoucang'
            "
          />
        </div>
        <ArrowRightOutlined class="app-card__arrow" />
      </div>
    </div>

    <LoginModal
      :visible="loginVisible"
      @onClose="loginVisible = false"
      @loginCallback="loginCallback"
    />
  </div>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  watch,
  toRaw,
  ref,
  h,
  onBeforeUnmount,
  createVNode,
} from "vue";
import request from "../../common/utils/request";
import store from "../../store/index";
import { useRoute, useRouter } from "vue-router";
import utils from "../../common/utils/utils";
import { Modal, notification, message } from "ant-design-vue";
import { ArrowRightOutlined, AppstoreOutlined } from "@ant-design/icons-vue";
export default defineComponent({
  name: "Create",
  components: { ArrowRightOutlined },

  setup() {
    const route = useRoute();
    const router = useRouter();
    const state = reactive({
      loginVisible: false,
      cateList: [],
      currentCateId: 0,
      appList: [],
      totalList: [],
    });

    const loginCallback = () => {
      state.loginVisible = false;
      router.go(0);
    };

    const getCategoryList = () => {
      return new Promise((resolve) => {
        state.cateList = [];
        request
          .get("/work_ai", "/application/industryCategory/list", {})
          .then((res) => {
            state.cateList = res.applicationList;
            // state.cateList.unshift({
            //   cat_name: "全部",
            //   id: 0,
            // });
            resolve();
          });
      });
    };

    const getAllApplications = (replaceList = true) => {
      request
        .get("/work_ai", "/pc/application/list", { is_industry: 0 })
        .then((res) => {
          state.cateList[0].application_total = res.list.length;
          if (replaceList) {
            state.appList = res.list;
          }
        });
    };

    const getAppList = (cateId) => {
      request
        .get("/work_ai", "/application/category/app_list", { cat_id: cateId })
        .then((res) => {
          state.appList = res.app_list;
        });
    };

    const onCateClick = (cate) => {
      let query = {};
      if (cate.id) {
        query = { cateId: cate.id };
      }
      router.push({
        name: "ApplicationHome",
        query: query,
      });
    };

    const onAppClick = (app) => {
      let params = {};
      if (state.currentCateId) {
        params = { cateId: state.currentCateId };
      } else if (app.top_cat_id) {
        params = { cateId: app.top_cat_id };
      }
      router.push({
        name: "Scene",
        params: params,
        query: {
          appId: app.id,
        },
      });
    };

    const init = () => {
      if (route.query.appId) {
        router.push(
          `/sceneModel/scene/${route.query.cateId}?appId=${route.query.appId}`
        );
        return;
      }

      if (route.query.cateId) {
        getCategoryList().then(() => {
          state.currentCateId = route.query.cateId;
          getAppList(route.query.cateId);
          getAllApplications(false);

          utils.checkLogin().then((isLogin) => {
            if (isLogin) {
              getUserCollectApps();
            }
          });
        });
      } else {
        getCategoryList().then(() => {
          getAllApplications();
          utils.checkLogin().then((isLogin) => {
            if (isLogin) {
              getUserCollectApps();
            }
          });
        });
      }
    };

    init();

    watch(
      () => route.query.cateId,
      (val) => {
        if (val) {
          state.currentCateId = route.query.cateId;
          getAppList(route.query.cateId);
        } else {
          state.currentCateId = 0;
          getAllApplications();
        }
      }
    );

    const collectApps = ref([]);
    const collectAppIds = computed(() => {
      return collectApps.value.map((app) => app.id);
    });

    const onCollectClick = (app) => {
      // 收藏功能需要先登录
      utils.checkLogin().then((isLogin) => {
        if (!isLogin) {
          state.loginVisible = true;
          return;
        }

        const status = collectAppIds.value.includes(app.id) ? 0 : 1;

        request
          .post("/work_ai", "/user/collect", {
            collect_type: "application",
            collect_id: app.id,
            status,
          })
          .then(() => {
            if (status) {
              collectApps.value.push(app);
            } else {
              collectApps.value = collectApps.value.filter(
                (item) => item.id !== app.id
              );
            }
          });
      });
    };

    const getUserCollectApps = async () => {
      const { data } = await request.get("/work_ai", "/user/collect/list", {
        type: "application",
      });
      collectApps.value = data.map((item) => item.collectable);
    };

    return {
      ...toRefs(state),
      loginCallback,
      onCateClick,
      onAppClick,
      collectAppIds,
      onCollectClick,
    };
  },
});
</script>

<style lang="less" scoped>
.create {
  width: 100%;
  height: 100%;
  padding: 0 20px;
  background-image: url(../home/home_bg.png);
  // background-size: cover;
  // background-position: center;
  // background-repeat: no-repeat;

  .cate-list {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    padding: 30px 0;

    .ant-badge {
      margin: 0 10px;
    }

    .cate-item {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      width: 80px;
      height: 80px;
      cursor: pointer;

      .cate-item-icon {
        width: 30px;
        height: 30px;
        object-fit: cover;
      }

      .cate-item-name {
        margin-top: 10px;
      }

      &:hover {
        background-color: rgba(0, 0, 0, 0.05);
        color: @primary-color;
        border-radius: 6px;
        -webkit-transform: translateY(-3px);
        -ms-transform: translateY(-3px);
        transform: translateY(-3px);
        transition: all 0.3s linear;
      }
    }

    .cate-item-current {
      background-color: rgba(0, 0, 0, 0.05);
      color: @primary-color;
      border-radius: 6px;
    }
  }

  .app-list {
    display: grid;
    gap: 20px;
    grid-template-columns: repeat(5, minmax(0, 1fr));
    padding-bottom: 30px;

    .app-card {
      border-radius: 10px;
      background: #fff;
      border: 1px solid #e9e9e9;
      width: 100%;
      padding: 20px 16px 30px;
      cursor: pointer;
      position: relative;

      &__image {
        width: 46px;
        height: 46px;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }

      &__title {
        margin-left: 10px;
        font-size: 16px;
        font-weight: 600;
      }

      &__info {
        margin-top: 20px;
        color: #767676;
        font-size: 12px;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }

      &__icon {
        position: absolute;
        right: 15px;
        top: 10px;
        display: none;

        &--shoucang {
          font-size: 16px;
        }
      }

      &__arrow {
        color: @primary-color;
        position: absolute;
        right: 15px;
        bottom: 10px;
        font-size: 16px;
        visibility: hidden;
      }

      &:hover {
        -webkit-transform: translateY(-3px);
        -ms-transform: translateY(-3px);
        transform: translateY(-3px);
        border: 1px solid @primary-color;

        .app-card__arrow {
          visibility: visible;
        }

        .app-card__icon {
          display: block;
        }
      }
    }
  }
}

@media (min-width: 1024px) {
  .app-list {
    grid-template-columns: repeat(3, minmax(0, 1fr)) !important;
  }
}

@media (min-width: 1280px) {
  .app-list {
    grid-template-columns: repeat(4, minmax(0, 1fr)) !important;
  }
}

@media (min-width: 1536px) {
  .app-list {
    grid-template-columns: repeat(5, minmax(0, 1fr)) !important;
  }
}
</style>
